﻿using ch05.binary.module;
using ch05.binary.type;

namespace ch05.binary.wasm_reader
{
    public partial struct WasmReader
    {
        // global sec
        private Global[] ReadGlobalSec()
        {
            var vec = new Global[ReadVarU32()];
            for (var i = 0; i < vec.Length; i++)
            {
                vec[i] = new Global
                {
                    Type = ReadGlobalType(),
                    Init = ReadExpr(),
                };
            }

            return vec;
        }

        // expr & instruction
        private Instruction[] ReadExpr()
        {
            var (instrs, end) = readInstructions();
            if (end != OpCodes.End)
            {
                Panic.Run("invalid expr end: {0:D}", end);
            }

            return instrs;
        }

        private GlobalType ReadGlobalType()
        {
            var gt = new GlobalType
            {
                ValType = ReadValType(),
                Mut = ReadByte(),
            };
            switch (gt.Mut)
            {
                case ConstData.MutConst:
                case ConstData.MutVar:
                    break;
                default:
                    Panic.Run("malformed mutability: %d", gt.Mut);
                    break;
            }

            return gt;
        }
    }
}